package com.luo.d3s.ec.infrastructure.event;

import com.luo.d3s.core.domain.event.DomainEvent;
import com.luo.d3s.core.domain.event.DomainEventPublisher;
import com.luo.d3s.ec.infrastructure.event.config.RabbitBaseConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 领域事件发送实现
 *
 * @author luohq
 * @date 2022-12-22 13:55
 */
@Component
@Slf4j
public class DomainEventPublisherImpl implements DomainEventPublisher {
    private RabbitTemplate rabbitTemplate;

    private List<RabbitBaseConfig> rabbitEventConfigs;


    public DomainEventPublisherImpl(RabbitTemplate rabbitTemplate, List<RabbitBaseConfig> rabbitEventConfigs) {
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitEventConfigs = rabbitEventConfigs;
    }

    @Override
    public void publish(DomainEvent event) {
        log.info("[DomainEventPublisher] publish event: {}", event);
        //使用RabbitMq发送事件
        this.rabbitEventConfigs.stream()
                //匹配DomainEvent类型名称与eventName，提取当前DomainEvent对应的MQ配置
                .filter(rabbitEventConfig -> event.getClass().getSimpleName().equals(rabbitEventConfig.getEventName()))
                //发送RabbitMq消息
                .forEach(rabbitEventConfig -> {
                    String exchangeName = rabbitEventConfig.getExchange().getName();
                    String routingKey = rabbitEventConfig.getExchange().getRoutingKey();
                    log.info("[RabbitMq SEND] exchange: {}, routingKey: {}, event: {}", exchangeName, routingKey, event);
                    this.rabbitTemplate.convertAndSend(exchangeName, routingKey, event);
                });
    }
}
